import { inject, reactive, ref } from 'vue'
import Configuration from '@/api/client/configuration.js'
import { SAVED_SUCCESSFULLY } from '@/constants/message.js'

export function useWiitransAccount(id, formRef) {
  const { message } = inject('Feedback')
  const wiitransAccount = reactive({
    account: ''
  })
  const wiitransAccountLoading = ref(false)
  const showWiitransAccountModal = ref(false)
  const wiitransAccountRules = {
    account: [
      {
        required: true,
        whitespace: true,
        message: 'Please input account',
        trigger: 'blur'
      }
    ]
  }
  const wiitransAccountForm = reactive({
    account: ''
  })
  const loadWiitransAccountInfo = () => {
    Configuration.getWiitransAccountInfo(id).then(({ data }) => {
      wiitransAccountLoading.value = false
      wiitransAccount.account = data.wiitransAccount
    })
  }
  loadWiitransAccountInfo()
  const handleEditWiitransAccount = () => {
    wiitransAccountForm.account = wiitransAccount.account
    showWiitransAccountModal.value = true
  }
  const handleSaveWiitransAccount = () => {
    formRef.value.validate().then(() => {
      wiitransAccountLoading.value = true
      Configuration.setWiitransAccountInfo(id, wiitransAccountForm.account)
        .then(() => {
          loadWiitransAccountInfo()
          message.success(SAVED_SUCCESSFULLY)
        })
        .finally(() => {
          showWiitransAccountModal.value = false
          wiitransAccountLoading.value = false
        })
    })
  }
  return {
    wiitransAccount,
    wiitransAccountLoading,
    showWiitransAccountModal,
    wiitransAccountRules,
    wiitransAccountForm,
    handleEditWiitransAccount,
    handleSaveWiitransAccount
  }
}
